package com.senseuni.da

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.elvishew.xlog.XLog
import com.senseuni.da.databinding.ActivityUpgradeBinding
import com.senseuni.da.db.AppDatabase
import com.senseuni.da.http.ApiDataSource
import com.senseuni.da.http.OnDownloadListener
import com.senseuni.da.model.LogType
import com.senseuni.da.utils.AppUtils
import com.senseuni.da.worker.AppLog
import java.io.File
import java.lang.Exception

class UpgradeActivity : AppCompatActivity() {

    lateinit var binding: ActivityUpgradeBinding

    lateinit var dataSource:ApiDataSource

    var lastProgress:Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or
//                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
//                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        binding = ActivityUpgradeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val id = intent.getLongExtra("id", 0)

        dataSource = ApiDataSource.instance

        if (id == 0L) {
            XLog.e("upgrade id loss,is:0")
            AppLog.instance.log(LogType.ERROR, "UpgradeActivity.upgrade id loss,is:0")
            this.onBackPressed()
            return
        }

        val upgrade = AppDatabase.getInstance().upgradeDao().findById(id)

        if (upgrade == null) {
            XLog.e("upgrade is null")
            AppLog.instance.log(LogType.ERROR, "UpgradeActivity.upgrade is null")
            this.onBackPressed()
            return
        }

        binding.tvCurrentVersion.text = getString(R.string.current_version, BuildConfig.VERSION_NAME)
        binding.tvLatestVersion.text = getString(R.string.latest_version, upgrade.version)

        if (upgrade.download && File(upgrade.localPath).exists()) {
            binding.tvProgress.text = "100%"
            binding.tvUpgradeTip.text = getString(R.string.upgrade_installing)
            val ret = AppUtils.install(upgrade.localPath)
            if (ret) {
                AppLog.instance.log(LogType.INFO, "UpgradeActivity.upgrade install success")
            } else {
                AppLog.instance.log(LogType.ERROR, "UpgradeActivity.upgrade install failed")
            }
            onBackPressed()
            return
        }

        dataSource.downloadApk(upgrade.url!!, object :
            OnDownloadListener {
            override fun onStart() {
                binding.tvProgress.text = "0%"
            }

            @SuppressLint("SetTextI18n")
            override fun onSuccess(filePath: String?) {
                XLog.d("download success")
                binding.tvProgress.text = "100%"

                binding.tvUpgradeTip.text = getString(R.string.upgrade_installing)
                val ret = AppUtils.install(filePath)
                if (ret) {
                    AppLog.instance.log(LogType.INFO, "UpgradeActivity.upgrade install success")
                } else {
                    AppLog.instance.log(LogType.ERROR, "UpgradeActivity.upgrade install failed")
                    onBackPressed()
                }
            }

            @SuppressLint("SetTextI18n")
            override fun onProgress(downloadSize: Long, totalSize: Long) {
                val temp:Int = ((downloadSize.toDouble() / totalSize.toDouble()) * 100).toInt()
                if (temp != lastProgress) {
                    XLog.d("download:${downloadSize}/${totalSize},progress:${temp}")
                    lastProgress = temp
                    binding.tvProgress.post {
                        binding.tvProgress.text = "${temp}%"
                    }
                }
            }

            override fun onFail(e: Exception?) {
                e?.printStackTrace()
                AppLog.instance.log(LogType.ERROR, "UpgradeActivity.upgrade failed: ${e?.message}")
                onBackPressed()
            }
        })


    }
}